package digital.store.springmvc.dao.impl;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;



import org.springframework.stereotype.Repository;

import digital.store.springmvc.dao.CategoryDao;
import digital.store.tutorial.springmvc.model.Category;

@Repository
public class CategoryDaoImpl implements CategoryDao {
	@PersistenceContext
	private EntityManager em;
	  
	public void saveOrUpdate(Category category) {
		if (category.getId() != null) {
	            em.merge(category);
	        } else {
	            em.persist(category);
	        }
	    }
	    
	public void delete(Long id) {
	    Category category = findById(id);
	    em.remove(category);
	    }
	    
	@SuppressWarnings("unchecked")
	public List<Category> findAll() {
	    return em.createQuery("SELECT c FROM Category c").getResultList();
	    }
	    
    public Category findById(Long id) {
        return em.find(Category.class, id);
    }
    
    @SuppressWarnings("unchecked")
    public List<String> findAllName()
    {
    	return em.createQuery("SELECT name FROM Category  GROUP BY name").getResultList();
    }
}
